package com.cskaoyan.controller.wx;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.pojo.MarketStorage;
import com.cskaoyan.service.SystemService;
import com.cskaoyan.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Tang_XueCheng
 * @description
 * @since 2022/04/08 23:13
 */
@RestController
@RequestMapping("wx")
public class WxStorageUploadController {

    @Autowired
    SystemService systemService;

    @RequestMapping("storage/upload")
    public BaseRespVo upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();

        // 解决文件名重复问题：用UUID工具类
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        // 获取原始文件的后缀
        String[] split = originalFilename.split("\\.");
        String finalFileName = uuid + "." + split[1];
        String relativePath = Constant.pictureLocation + finalFileName;
        // 将文件保存到本地
        File fileLocal = new File(Constant.staticResources + relativePath);
        if (!fileLocal.getParentFile().exists()) {
            fileLocal.getParentFile().mkdirs();
        }

        try {
            file.transferTo(fileLocal);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 将图片存入数据库，同时返回数据库记录
        MarketStorage marketStorage = systemService.storageCreate(file, finalFileName, relativePath);

        return BaseRespVo.ok(marketStorage);
    }
}

